﻿using AlibabaCloud.OpenApiClient.Models;
using AlibabaCloud.SDK.Dysmsapi20170525.Models;
using AlibabaCloud.TeaUtil.Models;
using Tea;

namespace ZGLXM.Read.Api.Utils
{
    public class SmsClientFactory
    {
        private readonly IConfiguration configuration;
        public SmsClientFactory(IConfiguration configuration)
        {
            this.configuration = configuration;
        }

        /// <summary>
        /// 创建短信发送客户端
        /// </summary>
        /// <returns></returns>
        private AlibabaCloud.SDK.Dysmsapi20170525.Client CreateClient()
        {
            var accessKeyId = configuration["Aliyun:AccessKeyId"];
            var accessSecret = configuration["Aliyun:AccessKeySecret"];

            var config = new Config
            {
                AccessKeyId = accessKeyId,
                AccessKeySecret = accessSecret,
                Endpoint = "dysmsapi.aliyuncs.com"
            };
            return new AlibabaCloud.SDK.Dysmsapi20170525.Client(config);
        }

        public void SendSms(string phoneNumber, string templateParam, string signName, string templateCode)
        {
            var client = CreateClient();
            var sendSmsRequest = new SendSmsRequest
            {
                SignName = signName,
                TemplateCode = templateCode,
                PhoneNumbers = phoneNumber,
                TemplateParam = templateParam,
            };

            var runtime = new RuntimeOptions();
            try
            {
                var response = client.SendSmsWithOptions(sendSmsRequest, runtime);
                Console.WriteLine("SMS sent successfully: " + response.Body);
            }
            catch (TeaException error)
            {
                // 记录错误信息
                Console.WriteLine("Error: " + error.Message);
                Console.WriteLine("Recommendation: " + error.Data["Recommend"]);
                AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
            }
            catch (Exception ex)
            {
                var error = new TeaException(new Dictionary<string, object>
                {
                    { "message", ex.Message }
                });
                // 记录错误信息
                Console.WriteLine("Error: " + error.Message);
                Console.WriteLine("Recommendation: " + error.Data["Recommend"]);
                AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
            }
        }
    }
}
